﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace EmailSender
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (rdoSPUtility.Checked)
                {
                    SendEmailUsingSharePoint();
                    MessageBox.Show("Email sent using SharePoint");
                }
                else
                {
                    SendEmailUsingSmtpClient();
                    MessageBox.Show("Email sent using SmtpClient");
                }
            }
            catch (Exception ex)
            {
                AddLog(ex.Message);
                AddLog(ex.StackTrace);
            }
        }

        private void SendEmailUsingSmtpClient()
        {
            SmtpClient client = new SmtpClient(txtSmtpHost.Text);
            client.Send(txtFrom.Text, txtToAddress.Text, txtSubject.Text, txtBody.Text);
        }        

        private void SendEmailUsingSharePoint()
        {
            using (SPSite site = new SPSite(txtSiteUrl.Text))
            {
                SPUtility.SendEmail(site.RootWeb, chkAppendHtmlTag.Checked, chkHtmEncode.Checked, txtToAddress.Text, txtSubject.Text, txtBody.Text);
            }
        }

        private void AddLog(string p)
        {
            txtLogs.Text = txtLogs.Text + p + "\r\n";
        }
    }
}
